package com.fvision.camera.appupgrade;

import java.io.File;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
//import android.support.v4.content.FileProvider;//v4注释
import v4.FileProvider;//v4注释 使用v4注释
import android.widget.Toast;

import com.fvision.camera.App;
import com.fvision.camera.BuildConfig;
import com.fvision.camera.R;
import com.fvision.camera.http.HttpRequest;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.Confecting;
import com.fvision.camera.utils.LogUtils;

public class UpgradeManager {
	private static UpgradeManager instance= null;
	private String download_address = null;
	private String description = null;
	private int versionCode = 0;
	private static Context mContext;

	private static NotificationManager manager;
	private static Notification notif;
	private static Notification.Builder builder3;
	private static String fileName = null;
	private String version = null;
	private int currentProgress = 0;

	public static final int FAIL = 0;
	public static final int COMPLETE = 1;
	public static final int PROGRESS = 2;

	private FileDownloadInterface mFileDownloadInterface = null;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
				case PROGRESS:
					int len = (Integer)msg.obj;
					currentProgress = len;
					builder3.setProgress(100, len, false);
					builder3.setContentInfo(len+"%");
					// notif.contentView.setTextViewText(R.id.content_view_text1, len+"%");
					//  notif.contentView.setProgressBar(R.id.content_view_progress, 100, len, false);
					if(len == 100){
						builder3.setOngoing(false);
						builder3.setContentInfo(mContext.getString(R.string.download_complete));
					}
					manager.notify(0, builder3.build());
					break;
				case FAIL:
					String content = (String)msg.obj;
					Toast.makeText(mContext, content, Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};

	public static UpgradeManager getInstance(){
		if(instance == null){
			instance = new UpgradeManager();
		}
		return instance;
	}

	public static void init(Context context,String fileName){
		mContext = context;
		UpgradeManager.fileName = fileName;
		//   notif.contentIntent = pIntent;
	}

	private void initNotif(){
		manager = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
//        notif = new Notification();
//        notif.icon = R.drawable.ic_launcher;
//        notif.tickerText = "App��";
//        //֪ͨ����ʾ���õ��Ĳ����ļ�
//        notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.upgrade_view);

		builder3 = new Notification.Builder(
				mContext);
		if (Build.VERSION.SDK_INT >= 26) {
			NotificationChannel channel = new NotificationChannel("616", "huiying",NotificationManager.IMPORTANCE_LOW);
			builder3.setChannelId("616");
			manager.createNotificationChannel(channel);
		}
		builder3.setSmallIcon(R.mipmap.ic_launcher)
				.setTicker(mContext.getString(R.string.app_upgrade))
				.setContentInfo(mContext.getString(R.string.downloading)+versionCode)
				.setOngoing(true)
				.setContentTitle(mContext.getString(R.string.app_upgrade))
				.setContentText(description);
		notif = builder3.build();
	}

	public void setOnProgressChangeListener(FileDownloadInterface fileDownloadInterface){
		mFileDownloadInterface = fileDownloadInterface;
	}

	public boolean update(int versionCode,String downloadAddress,String description,String versionName){
		version = versionName;
//		if(notif != null){
//			return false;
//		}

		download_address = downloadAddress;
		this.description = description;
		this.versionCode = versionCode;
		LogUtils.e("versionCode = "+versionCode + " "+getVersionCode());
		if(versionCode <= getVersionCode()){
            Toast.makeText(mContext, mContext.getString(R.string.is_the_latest_version), Toast.LENGTH_SHORT).show();
			return false;
		}
		showUpdateDialog();
		return true;
	}

	private void showUpdateDialog() {
		if(mContext == null){
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(getVersionName() +" -> "+ version);
		builder.setMessage(description);
		builder.setCancelable(false);

		builder.setPositiveButton(mContext.getString(R.string.ok), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					initNotif();
					downFile(download_address);     //������Ĵ����
				} else {
					Toast.makeText(mContext, mContext.getString(R.string.sdcard_prompt),
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		builder.setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		builder.create().show();
	}

	private void downFile(final String url) {
		manager.notify(0, notif);
		FileOper.download(url, CameraStateUtil.getSDCardCachePath(), UpgradeManager.fileName, new FileDownloadInterface() {

			@Override
			public void progress(float progress) {
				// TODO Auto-generated method stub
				LogUtils.e("progress = "+progress);
				Message msg = new Message();
				msg.what = PROGRESS;
				msg.obj = (int)progress;
				handler.sendMessage(msg);
				if(mFileDownloadInterface!=null){
					mFileDownloadInterface.progress(progress);
				}
			}

			@Override
			public void fail(int code, String error) {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = FAIL;
				msg.obj = error;
				handler.sendMessage(msg);
				if(mFileDownloadInterface!=null){
					mFileDownloadInterface.fail(code,error);
				}
			}

			@Override
			public void update(int version_code, String path, String app_desc, String version) {

			}

			@Override
			public void complete(String filepath) {
				// TODO Auto-generated method stub
				if(mFileDownloadInterface!=null){
					mFileDownloadInterface.complete(filepath);
				}
				LogUtils.e("progress = "+filepath);
				Message msg = new Message();
				msg.what = PROGRESS;
				msg.obj = 100;
				handler.sendMessage(msg);
				install(filepath);
			}
		});
	}

	//安装
	public void install(String url) {
		String str = "/"+fileName;
		String fileName = Environment.getExternalStorageDirectory() + str;
		Intent intent = new Intent(Intent.ACTION_VIEW);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
			intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileProvider", new File(fileName));
			intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
		}else {
			intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}

		mContext.startActivity(intent);
	}


	// 获取APP版本
	private int getVersionCode() {
		try {
			PackageManager packageManager = mContext.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(
					mContext.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}

	// 获取APP版本String
	private String getVersionName() {
		try {
			PackageManager packageManager = mContext.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(
					mContext.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void checkUpdate(){
//		final String appKey = "1889b37351288";
//		final String k_key = "key";
		HashMap<String, String> map = new HashMap<>();
//		map.put(k_key, appKey);
//		map.put("phone", "13480151236");
		if(App.isTestVersion){
			map.put("package",BuildConfig.APPLICATION_ID+".test");
		}else {
			map.put("package",BuildConfig.APPLICATION_ID+ Confecting.APP_UPGRADE_CHANNEL);
		}
		HttpRequest.requestGet(map, new HttpRequest.RequestIFace() {
			@Override
			public void onSuccess(int version_code, String path, String app_desc, String version) {
				if(mFileDownloadInterface!=null){
					mFileDownloadInterface.update(version_code,path,app_desc,version);
				}
			}

			@Override
			public void onFail(int errorCode, String error) {
				if(mFileDownloadInterface!=null){
					mFileDownloadInterface.fail(errorCode,error);
				}
			}
		});
	}
}
